package com.ganbo.myspring1.servlet;

import com.ganbo.myspring1.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * 6777888
 * Created by gan on 2020/5/2 21:34.
 */
public class GBDispatcherServlet extends HttpServlet {

    //缓存配置文件
    private Properties contextConfig = new Properties();

    //享元模式,缓存类名
    private List<String> classNames = new ArrayList<String>();

    //Ioc容器(Key默认是类名首字母消息,value就是对应的实例对象)
    private Map<String, Object> ioc = new HashMap<String, Object>();

    private Map<String, Method> handlerMapping = new HashMap();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //7、委派,根据URL去找到一个对应的Method并通过response返回
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception,Detail : " + Arrays.toString(e.getStackTrace()));
        }

    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");

        if (!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found!!!");
            return;
        }

        Map<String, String[]> params = req.getParameterMap();

        Method method = this.handlerMapping.get(url);


        //获取形参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] paramValues = new Object[parameterTypes.length];

        for (int i = 0; i < parameterTypes.length; i++) {
            Class paramterType = parameterTypes[i];
            if (paramterType == HttpServletRequest.class) {
                paramValues[i] = req;
            } else if (paramterType == HttpServletResponse.class) {
                paramValues[i] = resp;
            } else if (paramterType == String.class) {
                //通过运行时的状态去拿到你
                Annotation[][] pa = method.getParameterAnnotations();
                for (int j = 0; j < pa.length; j++) {
                    for (Annotation a : pa[i]) {
                        if (a instanceof GBRequestParam) {
                            String paramName = ((GBRequestParam) a).value();
                            if (!"".equals(paramName.trim())) {
                                String value = Arrays.toString(params.get(paramName)).replaceAll("\\[|\\]", "").replaceAll("\\s+", ",");
                                paramValues[i] = value;
                            }
                        }
                    }
                }
            }
        }
        //暂时硬编码
        String beanName = toLowerFirestCase(method.getDeclaringClass().getSimpleName());
        //赋值实参列表
        method.invoke(ioc.get(beanName), paramValues);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.扫描相关类
        doScanner(contextConfig.getProperty("scanPackage"));

        //==============IoC部分==============
        //3.初始化Ioc
        doInstance();

        //4.AOP,完成代理对象的生成

        //==============DI部分==============
        //5.完成依赖注入(DI)
        doAutowired();

        //==============MVC部分==============
        //6.初始化HandlerMapping
        doInitHandlerMapping();

        System.out.println("Gb Spring framework is init.");


    }

    //初始化HandlerMapping
    private void doInitHandlerMapping() {
        if (ioc.isEmpty()) return;

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if (!clazz.isAnnotationPresent(GBController.class)) continue;

            //相当于提取 class上配置的url
            String baseUrl = "";
            if (clazz.isAnnotationPresent(GBRequestMapping.class)) {
                baseUrl = clazz.getAnnotation(GBRequestMapping.class).value();
            }

            for (Method method : clazz.getMethods()) {
                if (!method.isAnnotationPresent(GBRequestMapping.class)) return;

                GBRequestMapping gbRequestMapping = method.getAnnotation(GBRequestMapping.class);
                // /user/hello
                String url = ("/" + baseUrl + "/" + gbRequestMapping.value()).replaceAll("/+", "/");
                handlerMapping.put(url, method);
                System.out.println("Mapped : " + url + "==method====>" + method);
            }

        }

    }

    //完成依赖注入(DI)
    private void doAutowired() {
        if (ioc.isEmpty()) return;

        Set<Map.Entry<String, Object>> entries = ioc.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            //把所有的包括private/protected/default/public 修饰字段都取出来
            for (Field field : entry.getValue().getClass().getDeclaredFields()) {
                if (!field.isAnnotationPresent(GBAutowired.class)) continue;

                GBAutowired autowired = field.getAnnotation(GBAutowired.class);

                //如果用户没有自定义beanName，就默认根据类型注入
                String beanName = autowired.value();
                if ("".equals(beanName)) {
                    beanName = field.getType().getName();//获取字段类型
                }

                //暴力访问111666
                field.setAccessible(true);

                try {
                    //ioc.get(beanName) 相当于通过接口的全名拿到接口的实现的实例
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //完成初始化Ioc容器工作
    private void doInstance() {
        if (classNames.isEmpty()) return;

        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);

                String beanName;
                if (clazz.isAnnotationPresent(GBController.class) || clazz.isAnnotationPresent(GBRepository.class)) {
                    GBController gbController = clazz.getAnnotation(GBController.class);
                    if (gbController != null) {
                        beanName = gbController.value();
                        if ("".equals(beanName)) {
                            beanName = toLowerFirestCase(clazz.getSimpleName());
                        }
                    } else {
                        GBRepository gbRepository = clazz.getAnnotation(GBRepository.class);
                        beanName = gbRepository.value();
                        if ("".equals(beanName)) {
                            beanName = toLowerFirestCase(clazz.getSimpleName());
                        }
                    }

                    ioc.put(beanName, clazz.newInstance());
                } else if (clazz.isAnnotationPresent(GBService.class)) {
                    //1.多个包下面出现了相同的类名,只能给自己取一个全局唯一的名字
                    beanName = clazz.getAnnotation(GBService.class).value(); //获取自定义Bean名字
                    Object instance = clazz.newInstance();
                    if ("".equals(beanName)) {
                        beanName = toLowerFirestCase(clazz.getSimpleName());
                    }
                    ioc.put(beanName, instance);

                    //2.如果有实现接口，默认接口名字对应的实现类为当前实例(这里主要是为了DI的时候面向接口编程)
                    //如果有多个实现类,只能抛异常
                    Class<?>[] interfaces = clazz.getInterfaces();
                    if (interfaces.length > 0) {
                        for (Class i : interfaces) {
                            if (ioc.containsKey(toLowerFirestCase(i.getSimpleName()))) {
                                throw new Exception("The " + i.getSimpleName() + " is Exists!!!");
                            }
                            ioc.put(i.getName(), instance);
                        }
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //将类名首字母小写作为IOC容器Bean名字
    private String toLowerFirestCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    //扫描相关类
    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());

        //当成是一个ClassPath文件夹
        for (File file : classPath.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                //全类名 = 包名.类名
                String className = (scanPackage + "." + file.getName().replace(".class", ""));
                //Class.forName(className);
                classNames.add(className);
//                System.out.println("===============className===>" + className);
            }
        }
    }


    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
